/**
 * Created by xqing on 2017/6/1.
 */
;(function (w, $) {
    function loginReg(opts) {
        var defaultOpts = {
            node: null
        };
        /**
         * 参数合并
         */
        this.opts = $.extend(defaultOpts, opts);
        /**
         * 请求地址
         * @type {{smsCode: string}}
         */
        this.url = {
            //获取验证码
            smsCode:'http://h5vote.sctv.com:28282/h5voteengine/getVrfCod.do',
            //注册
            reg:'http://h5vote.sctv.com:28282/h5voteengine/register.do',
            //快速登录
            quick:'http://h5vote.sctv.com:28282/h5voteengine/snsLogin.do',
            //普通登录
            login:'http://h5vote.sctv.com:28282/h5voteengine/authenUser.do'
        };
        /**
         * tag参数
         * @type {{pandaVideo: string, pandaWowtv: string, scfocus: string, iptvvote: string}}
         */
        this.tag={
            pandaVideo:"392861C427FE30420D959D043CD32FFD",
            pandaWowtv:"A9A2320BDB0006D83963CCFF2FF7E3A0",
            scfocus:"FAF092CD57FCF2F335AA0BD2658E817B",
            iptvvote:"189670BE1410EE9DA7DDD7E9DDFEFF7A",
            pc:"41357B790F3A7A90B2A529BEEF629C43"
        };

        /**
         * 是否使用mock数据
         * @type {boolean}
         */
        this.mock = false;

        /**
         * 获取短信验证码mock数据
         * @type {{comment: string, code: number}}
         */
        this.smsCodeMock = {
            "comment":"成功",
            "code":200
        };
        /**
         * 注册mock数据
         * @type {{comment: string, rslt: {uid: number, password: string, avatar: string, phone: string, nickname: null, pwdmodifydate: string, email: string, status: number, enabled: number}, code: number, token: string}}
         */
        this.regMock = {
            "comment": "成功",
            "rslt": {
                "uid": 11,
                "password": "e7631c07b2dc66c874cde0e0c4cfbe05",
                "avatar": "",
                "phone": "18689678909",
                "nickname": null,
                "pwdmodifydate": "2016-07-03 15:10:34",
                "email": "tets@qq.com",
                "status": 1,
                "enabled": 1
            },
            "code": 200,
            "token": "jxmtkn$$qNgojm1vCLwcyN7jZmheuw==$$11$$1467438230461$$604800000"
        };

        this._init();


    }
    $.extend(loginReg.prototype, {
        /**
         * 初始化入口
         * @private
         */
        _init: function () {
            var self = this;
            self._bind();

        },
        /**
         * 事件绑定
         * @private
         */
        _bind: function () {
            var self = this;
            var wrapper = $(self.opts.node);
            var regPop = $('#j-reg,#j-login');
            //移除error效果
            $('body').delegate('input.error','keyup',function(){
                var $this = $(this);
                $this.removeClass('error');
            });
            $('body').delegate('input.error','change',function(){
                var $this = $(this);
                $this.removeClass('error');
            });
            //读取cookie
            function getCookie(name) {
                var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
                if(arr=document.cookie.match(reg))
                    return unescape(arr[2]);
                else
                    return null;
            }
            // console.log(getCookie('userToken'));


            //获取验证码
            regPop.delegate('.j-get-sms.active','click',function () {
                var $this = $(this);
                var node = $this.parents('.card-reg,.card-quick');
                var tips = $this.parents('.popup_content').find('.tips');

                if(self._checkTel(node.find('input.phone'))){
                    if(self.mock){
                        tips.text(self.smsCodeMock.comment).removeClass('hide');

                    }else {
                        // 按钮倒计时逻辑
                        var step = 180;
                        $this.text('重新发送180').css('color','#ddd').removeClass('active');//有active则可以点击，没有则不行
                        var _res = setInterval(function() {
                            $this.text('重新发送'+step);
                            step-=1;
                            if(step <= 0){
                                $this.addClass('active').css('color','#55b0b5');//有active则可以点击，没有则不行
                                $this.text('获取验证码');
                                clearInterval(_res);//清除setInterval
                            }
                        },1000);

                        // 获取验证码请求
                        $.ajax({
                            type: "post",
                            url: self.url.smsCode,
                            data: JSON.stringify(self._smsJson(node)),
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            success: function(data){
                                tips.text(data.comment).removeClass('hide');
                                //获取验证码没有回调函数
                            }
                        });
                    }
                }
            });

            //注册按钮
            regPop.delegate('.j-reg-btn','click',function () {
                var $this = $(this);
                var node = $this.parents('.card-reg');
                if(self._checkMust(node.find('input.must')) && self._checkTel(node.find('input.phone'))){
                    if(self.mock){
                        self._loginSuccJson(self.regMock);
                    }else {
                        $.ajax({
                            type: "post",
                            url: self.url.reg,
                            data: JSON.stringify(self._regJson(node)),
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            success: function(data){
                                self._loginSuccJson(data,node);
                            }
                        });
                    }
                }

            });
            //快速登录-登录按钮
            regPop.delegate('.j-quick-btn','click',function () {
                var $this = $(this);
                var node = $this.parents('.card-quick');
                if(self._checkMust(node.find('input.must')) && self._checkTel(node.find('input.phone'))){
                    if(self.mock){
                        self._loginSuccJson(self.regMock);
                    }else {
                        $.ajax({
                            type: "post",
                            url: self.url.quick,
                            data: JSON.stringify(self._quickJson(node)),
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            success: function(data){
                                self._loginSuccJson(data,node);
                            }
                        });
                    }
                }

            });
            //登录-登录按钮
            regPop.delegate('.j-login-btn','click',function () {
                var $this = $(this);
                var node = $this.parents('.card-login');
                if(self._checkMust(node.find('input.must')) && self._checkTel(node.find('input.phone'))){
                    if(self.mock){
                        self._loginSuccJson(self.regMock);
                    }else {
                        $.ajax({
                            type: "post",
                            url: self.url.login,
                            data: JSON.stringify(self._loginJson(node)),
                            contentType: "application/json;charset=utf-8",
                            dataType: "json",
                            success: function(data){
                                self._loginSuccJson(data,node);
                            }
                        });
                    }
                }


            });



        },
        /**
         * 检查手机号
         * @param node
         * @returns {boolean}
         * @private
         */
        _checkTel: function (node) {
            var tel = node.val();
            var reg = /^0?1[0-9][0-9]\d{8}$/;
            if (reg.test(tel)) {
                return true;
            }else{
                node.addClass('error');
                return false;
            }
        },
        /**
         * 必填项检查
         * @param node
         * @private
         */
        _checkMust: function (node) {
            var flag = true;
            $(node).each(function (i) {
                var checkTxt = $.trim($(node[i]).val());
                if(checkTxt == ''){
                    $(node[i]).addClass('error');
                    flag = false;
                    return false;
                }else {
                    flag = true;
                }
            });
            return flag;

        },
        /**
         * 短信验证码请求json
         * @param node
         * @returns {{}}
         * @private
         */
        _smsJson: function(node){

            var smsJson = {};
            var user = node.find('input.phone');
            smsJson['UserID'] = user.val();
            if(node.hasClass('card-reg')){
                smsJson['Type'] = 'reg';
            }else if(node.hasClass('card-quick')){
                smsJson['Type'] = 'quick';
            }
            return smsJson;
        },
        /**
         * 注册请求json
         * @param node
         * @returns {{}}
         * @private
         */
        _regJson: function (node) {
            var self= this;
            var regJson = {};
            var user = node.find('input.phone');
            var pwd = node.find('input.pwd');
            var code = node.find('input.code');
            var nowStamp = new Date().getTime();
            regJson.Stamp = nowStamp + '';
            regJson.Uid = user.val();
            regJson.PWD = pwd.val();
            regJson.VCode = code.val();
            var wurl = window.document.URL;
            if(wurl.indexOf('http://app.sctv.com/') > -1){
                regJson.Tag = self.tag.pandaVideo;
            }else {
                regJson.Tag = self.tag.pc ;
            }
            // console.log(regJson);
            return regJson;
        },
        /**
         * 快读登录请求json
         * @param node
         * @returns {{}}
         * @private
         */
        _quickJson: function (node) {
            var self= this;
            var quickJson = {};
            var user = node.find('input.phone');
            var pwd = node.find('input.pwd');
            var code = node.find('input.code');
            var nowStamp = new Date().getTime();
            quickJson.Stamp = nowStamp + '';
            quickJson.Uid = user.val();
            quickJson.VCode = code.val();

            var wurl = window.document.URL;
            if(wurl.indexOf('http://app.sctv.com/') > -1){
                quickJson.Tag = self.tag.pandaVideo;
            }else {
                quickJson.Tag = self.tag.pc ;
            }

            // console.log(quickJson);
            return quickJson;
        },
        /**
         *
         * @param node
         * @returns {{}}
         * @private
         */
        _loginJson: function (node) {

            var self= this;
            var loginJson = {};
            var user = node.find('input.phone');
            var pwd = node.find('input.pwd');
            var code = node.find('input.code');
            var nowStamp = new Date().getTime();
            loginJson.Stamp = nowStamp + '';
            loginJson.Uid = user.val();
            loginJson.PWD = pwd.val();
            var wurl = window.document.URL;
            if(wurl.indexOf('http://app.sctv.com/') > -1){
                loginJson.Tag = self.tag.pandaVideo;
            }else {
                loginJson.Tag = self.tag.pc ;
            }
            // console.log(loginJson);
            return loginJson;
        },

        /**
         * 注册，登录，快速登录成功回调
         * @param returnJson
         * @private
         */
        _loginSuccJson: function (returnJson,node) {

            var self = this;
            var username = $('.login');
            if(returnJson.code == 200){
                var userId = returnJson.rslt.phone;
                var userToken = returnJson.token;

                username.find('.user-id').html(userId);
                username.data('user-id',userId);
                username.removeClass('hide');
                // $('.btn-box').addClass('hide');
                // $('#formhide').val(userId);
                // $('#j-reg').addClass('hide');
                // $('#j-login').addClass('hide');

                // 写入cookie
                function setCookie(name,value) {
                    var Days = 30;
                    var exp = new Date();
                    exp.setTime(exp.getTime() + Days*24*60*60*1000);
                    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
                }
                setCookie('userToken',userToken);
                setCookie('userId',userId);
                // window.location.reload();
                window.location.href = 'web_game/?token='+userToken

            }else {
                $(node).find('.tips').text(returnJson.comment).removeClass('hide');
            }

        },


        /**
         * 重新加载
         */
        reload: function () {
            this._init();
        }
    });

    /**
     * 暴露全局变量
     */
    if (!w.loginReg) {
        w.loginReg = function () {
            $('.j_loginreg').each(function () {
                new loginReg({
                    node: this
                });

            });
        };
    }

    /**
     * banner入口
     */
    $(function () {
        w.loginReg();
    });

})(window, jQuery);